package com.service.business.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.sms.MessageStatus;
import com.nexmo.client.sms.SmsSubmissionResponse;
import com.nexmo.client.sms.SmsSubmissionResponseMessage;
import com.nexmo.client.sms.messages.TextMessage;
import com.service.business.utils.HttpUtil;
import com.service.core.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <dl>
 * <dt>platform</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2018</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019-04-03</dd>
 * </dl>
 */
@Slf4j
@Component
public class MessageSender {

    @Autowired
    private SMSConf smsConf;
    /**
     * 中国
     */
    private static String chUrl = "http://utf8.api.smschinese.cn/?Uid=lsq281647998&Key=d41d8cd98f00b204e980&smsMob={smsMob}&smsText={smmText}";

    private static String chJuHeUrl = "http://v.juhe.cn/sms/send";

    private static String juHeKey = "e1254662f93d9d432c38fc772464ebb8";

    public Integer send(String smsMob, String phoneCode, String smsText, String tplId) {
        //Language.LANG.get() == null || I18nUtil.CLocale.zh_CN.equals(Language.LANG.get()) ||
        if (StringUtils.equals("+86", phoneCode) || StringUtils.equals("86", phoneCode)) {
//            return sendCh(smsMob, smsText);
            return sendChByJuhe(smsMob,smsText,tplId);
        } else {
            return sendInNexmo(smsMob, phoneCode, smsText);
        }
    }

    /**
     * 中国send
     * 返回值
     *-1	没有该用户账户
     * -2	接口密钥不正确 [查看密钥]不是账户登陆密码
     * -21	MD5接口密钥加密不正确
     * -3	短信数量不足
     * -11	该用户被禁用
     * -14	短信内容出现非法字符
     * -4	手机号格式不正确
     * -41	手机号码为空
     * -42	短信内容为空
     * -51	短信签名格式不正确 接口签名格式为：【签名内容】
     * -52	短信签名太长 建议签名10个字符以内
     * -6	IP限制
     * 大于0	短信发送数量
     * @param smsMob
     * @param smsText
     */
    private Integer sendCh(String smsMob, String smsText) {
        String result = null;
        try {
            int rst = 0;
            String URL = smsConf.getCnSmsUrl().replace("{smsMob}", smsMob).replace("{smmText}", URLEncoder.encode(smsText,"UTF-8"));
            result = HttpUtil.get(URL);
            if(!"".equals(result) && result != null){
                rst = Integer.parseInt(result);
            }else{
                throw new CommonException("短信发送失败，请稍后重试","msg_send_error");
            }

            if(rst > 0){
                log.info("MessageSender.sendCh, smsMob:{}, smsText:{} ==> 验证码发送成功！", smsMob, smsText);
                return 1;
            }else{
                log.info("MessageSender.sendCh, 接口商返回错误，错误代码:{}, smsMob:{}, smsText:{}", rst, smsMob, smsText);
                throw new CommonException("短信发送失败，请稍后重试", "msg_send_error");
            }
        } catch (Exception e) {
            log.info("MessageSender.sendCh, smsMob:{}, smsText:{}, body:{}", smsMob, smsText, result);
            return -1;
//            throw new CommonException("短信发送失败，请稍后重试", "msg_send_error");
        }
    }

    private static Integer sendChByJuhe(String mobile, String tpl_value, String tplId) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("mobile", mobile);
        params.put("tpl_id", tplId);
        params.put("tpl_value", "#code#="+tpl_value);
        params.put("key", juHeKey);
        String result = "";
        try {
            result = HttpUtil.post(chJuHeUrl, params);
            log.info("MessageSender.sendChByJuhe, mobile:{}, tpl_value:{}, result:{}", mobile, tpl_value, result);
            JSONObject resultObj = JSON.parseObject(result);
            if (StringUtils.equals("0", resultObj.getString("error_code"))) {
                return 1;
            }
            return -1;
        } catch (Exception e) {
            log.info("MessageSender.sendChByJuhe, mobile:{}, tpl_value:{}, send error", mobile, tpl_value);
            return -1;
        }
    }

    private static final String InUrl = "https://api.mysubmail.com/internationalsms/send.json";


    /**
     * NEXMO 版本的国际短信发送
     * @param smsMob
     * @param phoneCode
     * @param smsText
     * @return
     */
    private static Integer sendInNexmo(String smsMob, String phoneCode, String smsText) {
        NexmoClient client = new NexmoClient.Builder()
                .apiKey("6df4e7c3")
                .apiSecret("9hUUIQq5AI0XIZ1s")
                .build();


        String from = "FINDCLOUD";
        if(StringUtils.equals("+1", phoneCode) || StringUtils.equals("1", phoneCode)) {
            //美国电话发短信，必须用from电话号码发送
            from = "19592068636";
            smsText = "[FINDCLOUD]"+smsText;
        }

        try {
            TextMessage message = new TextMessage(from, phoneCode + smsMob, smsText,true);

            SmsSubmissionResponse response = client.getSmsClient().submitMessage(message);

            //可能有多条发送，一并返回结果集，遍历获取发送结果
            for (SmsSubmissionResponseMessage responseMessage : response.getMessages()) {
                MessageStatus status = responseMessage.getStatus();//状态，OK
                BigDecimal remainingBalance = responseMessage.getRemainingBalance();//剩下余额
                BigDecimal messagePrice = responseMessage.getMessagePrice();//此短信花费价格
                if (!MessageStatus.OK.equals(status)) {
                    //短信发送不成功
                }else{
                    //短信发送成功
                }
                log.info("NEXMO,RST {}:",responseMessage.toString());
            }
            return 1;
        } catch (Exception e) {
            log.error("请求异常：" + e);
            return -1;
        }
    }
    /**
     * 国际
     *
     * @param smsMob
     * @param smsText
     */
    private static Integer sendIn(String smsMob, String phoneCode, String smsText) {
        //API账号，50位以内。必填
        String account = "60637";
        //API账号对应密钥，联系客服获取。必填
        String password = "c55624795b41029bbd8b0900144f063d";

        //短信内容。长度不能超过536个字符。必填
        String msg = smsText;

        //手机号码，格式(区号+手机号码)，例如：8615800000000，其中86为中国的区号，区号前不使用00开头,15800000000为接收短信的真实手机号码。5-20位。必填
        String mobile = phoneCode + smsMob;


        Map map = new HashMap();
        map.put("appid", account);
        map.put("signature", password);
        map.put("content", msg);
        map.put("to", mobile);


        log.info("请求参数为:" + map.toString());
        try {
            String result = HttpUtil.postTxt(InUrl, map);

            log.info("返回参数为:" + result);

            JSONObject jsonObject = JSON.parseObject(result);
            String status = jsonObject.get("status").toString();
            if (!"success".equals(status)) {
                throw new CommonException("短信发送失败，请稍后重试", "msg_send_error");
            }
            return 1;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("请求异常：" + e);
            return -1;
        }
    }

    public static void main(String[] args) {

    }
}
